import 'package:flutter_design/com/qlslylq/flutterdesign/constant/HttpConstant.dart';
import 'package:flutter_design/com/qlslylq/flutterdesign/bean/User.dart';
import 'package:flutter_design/com/qlslylq/flutterdesign/util/SPUtils.dart';
import 'package:flutter_design/com/qlslylq/flutterdesign/util/TextUtils.dart';
import 'dart:convert';

/*
 * User单例操作封装<br/> 
 */
class UserMethod {

  /*
   * 单例user
   */
  static User user;

  /*
   * 缓存token到属性文件中并更新BaseConstant中的内存token<br/>
   */
  static void setToken(String token) {
    SPUtils.put(SPUtils.MEMBER_TOKEN, token);
    HttpConstant.TOKEN = token;
  }

  /*
   * 从属性文件中获取token<br/>
   */
  static String getTokenFromProperty() {
    Object token = SPUtils.get(SPUtils.MEMBER_TOKEN, "");
    if (token == null || TextUtils.isEmpty(token.toString())) {
      return null;
    } else {
      return token.toString();
    }
  }

  /*
   * 设置当前用户<br/>
   */
  static void setUser(User user) {
    UserMethod.user = user;
    SPUtils.put(SPUtils.MEMBER_INFO, json.encode(user));
  }

  /*
   * 获取当前用户<br/>
   * 如果页面内点击清除缓存则需要在此处处理null问题<br/>
   * 兼容强制登录与按需登录<br/>
   */
  static User getUser() {
    if (user == null) {
      String user_json = SPUtils.get(SPUtils.MEMBER_INFO, "{}");
      user = json.decode(user_json);
    }
    return user;
  }

  /*
   * 获取当前用户id<br/>
   */
  static String getUserId() {
    return getUser().id;
  }

}
